Source Code Viewer - Example 4 - FormatLibrary

package name.matthewgreet.example4.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.opensymphony.xwork2.interceptor.ValidationAware;

import name.matthewgreet.example4.action.ViewGameListAction.GameCategory;
import name.matthewgreet.example4.dto.ArtistDTO;
import name.matthewgreet.example4.dto.DesignerDTO;
import name.matthewgreet.example4.dto.MechanicDTO;
import name.matthewgreet.example4.dto.PublisherDTO;

/**
 * Static library functions for formatting data for display but also parsing them for validation. 
 */
public class FormatLibrary {
    private static final String DATE_FORMAT_LONG_YEAR = "dd/MM/yyyy";
	private static final String NUMBER_FORMAT = "##,###,###";
	
	public static String formatCategoriesText(boolean hasAbstract, boolean hasChildren, boolean hasCustomizable, boolean hasFamily, 
			boolean hasParty, boolean hasStrategy, boolean hasThematic, boolean hasWar) {
		String result;
		
		result = "";
		if (hasAbstract) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.ABSTRACT);
		}
		if (hasChildren) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.CHILDREN);
		}
		if (hasCustomizable) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.CUSTOMIZABLE);
		}
		if (hasFamily) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.FAMILY);
		}
		if (hasParty) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.PARTY);
		}
		if (hasStrategy) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.STRATEGY);
		}
		if (hasThematic) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.THEMATIC);
		}
		if (hasWar) {
			if (result.length() > 0) 
				result += ", ";
			result += formatGameCategory(GameCategory.WAR);
		}
		return result;
	}
	
	public static String formatArtistsText(Collection<ArtistDTO> artists, boolean hasOthers, boolean useHTMLNonBreakingSpace) {
		List<ArtistDTO> sortedArtists;
		String result;
		
		result = "";
		if (artists != null) {
			sortedArtists = new ArrayList<>(artists);
			Collections.sort(sortedArtists, (a1,a2) -> a1.getName().compareToIgnoreCase(a2.getName()));
			for (ArtistDTO artist: sortedArtists) {
				if (result.length() > 0) 
					result += ", ";
				if (useHTMLNonBreakingSpace) {
					result += artist.getName().replace(" ", "&nbsp;");
				} else {
					result += artist.getName();
				}
			}
			if (hasOthers) {
				if (result.length() > 0) 
					result += ", ";
				result += "Others";
			}
		}
		return result;
	}

    /**
     * Returns formatted date in DD/MM/YYYY without time component.
     */
    public static synchronized String formatDateLongYear(Date value) {
        DateFormat formatter;
        
        if (value != null) {
            formatter = new SimpleDateFormat(DATE_FORMAT_LONG_YEAR);
            return formatter.format(value);
        } else {
            return "";
        }
    }
    
	public static String formatDesignersText(Collection<DesignerDTO> designers, boolean hasOthers, boolean useHTMLNonBreakingSpace) {
		List<DesignerDTO> sortedDesigners;
		String result;
		
		result = "";
		if (designers != null) {
			sortedDesigners = new ArrayList<>(designers);
			Collections.sort(sortedDesigners, (d1,d2) -> d1.getName().compareToIgnoreCase(d2.getName()));
			for (DesignerDTO designer: sortedDesigners) {
				if (result.length() > 0) 
					result += ", ";
				if (useHTMLNonBreakingSpace) {
					result += designer.getName().replace(" ", "&nbsp;");
				} else {
					result += designer.getName();
				}
			}
			if (hasOthers) {
				if (result.length() > 0) 
					result += ", ";
				result += "Others";
			}
		}
		return result;
	}

	public static String formatGameCategory(GameCategory preferredCategory) {
		switch (preferredCategory) {
		case ABSTRACT:		return "Abstract";
		case ALL:			return "Overall";
		case CHILDREN:		return "Children's";
		case CUSTOMIZABLE:	return "Customizable";
		case FAMILY:		return "Family";
		case PARTY:			return "Party";
		case STRATEGY:		return "Strategy";
		case THEMATIC:		return "Thematic";
		case WAR:			return "War";
		}
		return "";
	}
	
	public static String formatGameWeight(BigDecimal gameWeight) {
		return gameWeight.setScale(1, RoundingMode.HALF_UP).toString();
	}
	
	public static String formatGameWeightDesc(BigDecimal gameWeight) {
		String result;
		
		if (gameWeight.floatValue() >= 1.0 && gameWeight.floatValue() < 2.0) {
			result = "Light";
		} else if (gameWeight.floatValue() >= 2.0 && gameWeight.floatValue() < 3.0) {
			result = "Light-Medium";
		} else if (gameWeight.floatValue() >= 3.0 && gameWeight.floatValue() < 4.0) {
			result = "Medium";
		} else if (gameWeight.floatValue() >= 4.0 && gameWeight.floatValue() < 4.5) {
			result = "Medium-Heavy";
		} else if (gameWeight.floatValue() >= 4.5 && gameWeight.floatValue() < 5) {
			result = "Heavy";
		} else {
			result = "";
		}
		return result;
	}
	
	public static String formatMechanicsText(Collection<MechanicDTO> mechanics, boolean useHTMLNonBreakingSpace) {
		List<MechanicDTO> sortedMechanics;
		String result;
		
		result = "";
		if (mechanics != null) {
			sortedMechanics = new ArrayList<>(mechanics);
			Collections.sort(sortedMechanics, (m1,m2) -> m1.getName().compareToIgnoreCase(m2.getName()));
			for (MechanicDTO mechanic: sortedMechanics) {
				if (result.length() > 0) 
					result += ", ";
				if (useHTMLNonBreakingSpace) {
					result += mechanic.getName().replace(" ", "&nbsp;");
				} else {
					result += mechanic.getName();
				}
			}
		}
		return result;
	}

	public static String formatNumber(Integer value) {
		if (value != null) {
			return (new DecimalFormat(NUMBER_FORMAT)).format(value);
		} else {
			return "";
		}
	}
	
	public static String formatPublishersText(Collection<PublisherDTO> publishers, boolean hasOthers, boolean useHTMLNonBreakingSpace) {
		List<PublisherDTO> sortedPublishers;
		String result;
		
		result = "";
		if (publishers != null) {
			sortedPublishers = new ArrayList<>(publishers);
			Collections.sort(sortedPublishers, (p1,p2) -> p1.getName().compareToIgnoreCase(p2.getName()));
			for (PublisherDTO publisher: sortedPublishers) {
				if (result.length() > 0) 
					result += ", ";
				if (useHTMLNonBreakingSpace) {
					result += publisher.getName().replace(" ", "&nbsp;");
				} else {
					result += publisher.getName();
				}
			}
			if (hasOthers) {
				if (result.length() > 0) 
					result += ", ";
				result += "Others";
			}
		}
		return result;
	}

	public static String formatRating(BigDecimal rating) {
		if (rating.stripTrailingZeros().scale() <= 0) {
			return rating.stripTrailingZeros().toPlainString();
		} else {
			return rating.toString();
		}
	}
	
	public static String formatUserRating(BigDecimal userRating) {
		return userRating.setScale(1, RoundingMode.HALF_UP).toString();
	}
	
	public static String formatUserRatingDesc(BigDecimal userRating) {
		String result;

		result = "";
		switch (userRating.intValue()) {
		case 0:
			result = "Unrated";
			break;
		case 1:
			result = "Awful - defies game description";
			break;
		case 2:
			result = "Very Bad - won't play ever again";
			break;
		case 3:
			result = "Bad - likely won't play this again";
			break;
		case 4:
			result = "Not so good - but could play again";
			break;
		case 5:
			result = "Mediocre - take it or leave it";
			break;
		case 6:
			result = "Ok - will play if in the mood";
			break;
		case 7:
			result = "Good - usually willing to play";
			break;
		case 8:
			result = "Very good - enjoy playing and would suggest it";
			break;
		case 9:
			result = "Excellent - very much enjoy playing";
			break;
		case 10:
			result = "Outstanding - will always enjoy playing";
			break;
		}
		return result;
	}
	
    public static<T extends Enum<T>> T parseRequiredEnum(String field, Class<T> enumType,
            ValidationAware validationAware, String requiredMessage, String notEnumMessage) {
        T result = null;
        
        if (field == null || field.length() == 0) {
            validationAware.addActionError(requiredMessage);
        } else {
            try {
                result = Enum.valueOf(enumType, field);
            }
            catch (IllegalArgumentException e) {
                validationAware.addActionError(notEnumMessage);
            }
        }
        return result;
    }
    

	public static Integer parseInteger(String value, ValidationAware validationAware, String notNumberMessage) {
		if (value != null && value.trim().length() > 0) {
			try {
				return Integer.parseInt(value);
			}
			catch (NumberFormatException e) {
				validationAware.addActionError(notNumberMessage);
			}
		}
		return null;
	}

    public static int parseRequiredInt(String field, ValidationAware validationAware, 
            String requiredMessage, String notIntMessage) {
        int result = 0;
        
        if (field == null || field.trim().length() == 0) {
            validationAware.addActionError(requiredMessage);
        } else {
            try {
				result = Integer.parseInt(field);
            }
            catch (NumberFormatException e) {
                validationAware.addActionError(notIntMessage);
            }
        }
        return result;
    }
    

}